import {AfterViewInit, Component, ElementRef, NgZone, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {fromEvent, Subject} from 'rxjs';
import {auditTime} from 'rxjs/operators';

@Component({
  selector: 'app-cube',
  templateUrl: './cube.component.html',
  styleUrls: ['./cube.component.scss']
})
export class CubeComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('canvasRef') canvasRef: ElementRef;

  private _destroy$ = new Subject();

  constructor(private ngZone: NgZone) { }

  ngOnInit(): void {
  }

  ngAfterViewInit() {
    import('./cube-render').then(module => {
      this.ngZone.runOutsideAngular(_=> {
        const canvasEl = this.canvasRef.nativeElement as HTMLCanvasElement;
        const cubeRender = new module.CubeRender(canvasEl);
        const render = () => {
          cubeRender.cubeMesh.rotation.x += 0.02;
          cubeRender.cubeMesh.rotation.y += 0.02;
          cubeRender.cubeMesh.rotation.z += 0.02;
          window.requestAnimationFrame(render);
          cubeRender.render();
        };

        cubeRender.initDisplay();
        cubeRender.resizeDisplay();
        cubeRender.initCube().then(() => {
          cubeRender.resizeDisplay();
          render();
        }).catch(() => {});

        fromEvent(window, 'resize')
          .pipe(auditTime(500))
          .subscribe(() => {
            cubeRender.resizeDisplay();
          });
      })
    });
  }

  ngOnDestroy() {
    this._destroy$.next();
    this._destroy$.complete();
  }

}
